﻿using System.Data;
using System.Data.Entity;
using System.Data.Entity.Migrations;

namespace Common.Framework.CommonDAL
{
    /// <summary>
    ///     实体状态设置
    /// </summary>
    public class SetEntityState
    {
        public SetEntityState(DbContext context)
        {
            this._context = context;
        }

        private DbContext _context { get; set; }

        /// <summary>
        ///     设置实体状态
        /// </summary>
        /// <typeparam name="T">T class</typeparam>
        /// <param name="entity">Entity</param>
        /// <param name="state">EntityState</param>
        public void SetState<T>(T entity, EntityState state) where T : class
        {
            this._context.Entry(entity).State = state;
        }

        /// <summary>
        ///     设置为修改状态
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        public void Update<T>(T entity) where T : class
        {
            //entity = this._context.Entry(entity).Entity;
            //this._context.Set<T>().Attach(entity);
            //this.SetState(entity, EntityState.Modified);
            this._context.Set<T>().AddOrUpdate(entity);
        }

        /// <summary>
        ///     设置为删除状态
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        public void Delete<T>(T entity) where T : class
        {
            //entity = this._context.Entry(entity).Entity;
            //this._context.Set<T>().Attach(entity);
            //this._context.Set<T>().Remove(entity);
            //this.SetState(entity, EntityState.Deleted);
            this._context.Entry(entity).State = EntityState.Deleted;
        }

        /// <summary>
        ///     设置为添加状态
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        public void Add<T>(T entity) where T : class
        {
            this._context.Set<T>().Add(entity);
            //this._context.Set<T>().Add(entity);
            //this._context.Entry(entity).State = EntityState.Added;
        }


        /// <summary>
        ///设置为添加状态
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        public void AddOrUpdate<T>(T entity) where T : class
        {
            this._context.Set<T>().AddOrUpdate(entity);
            //this.SetState(entity, EntityState.Modified);
        }
    }
}